﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Domain.Repositories;

namespace PasteLoggerBoard.usermodels
{
    /// <summary>
    /// 用户信息
    ///</summary>
    [TypeFilter(typeof(RoleAttribute), Arguments = new object[] { "data", "add" })]
    public class UserInfoAppService : IUserAppService
    {

        private readonly IPasteLoggerBoardDbContext _dbContext;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="dbcontext"></param>
        public UserInfoAppService(IPasteLoggerBoardDbContext dbcontext) : base()
        {
            _dbContext = dbcontext;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="page"></param>
        /// <param name="size"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<PagedResultDto<UserInfoListDto>> GetListAsync(int page = 1, int size = 20)
        {
            var query = _dbContext.UserInfo.Where(t => 1 == 1).OrderBy(xy => xy.Id);
            var _pagedto = new PagedResultDto<UserInfoListDto>();
            _pagedto.TotalCount = await query.CountAsync();
            var userList = await query.Page(page, size).AsNoTracking().ToListAsync();
            var temList = ObjectMapper.Map<List<UserInfo>, List<UserInfoListDto>>(userList);
            var uids = temList.Select(t => t.Id).ToList();
            _pagedto.Items = temList;
            return _pagedto;
        }

        /// <summary>
        /// 根据ID获取单项用户信息
        ///</summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public UserInfoDto GetByIdAsync(int id)
        {
            var query = _dbContext.UserInfo.Where(t => t.Id == id)
                .FirstOrDefault();
            var temList = ObjectMapper.Map<UserInfo, UserInfoDto>(query);
            return temList;
        }

        /// <summary>
        /// 根据ID获取待更新单项信息用户信息
        ///</summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<UserInfoDto> GetInfoForUpdateAsync(int id)
        {
            var query = await _dbContext.UserInfo.Where(t => t.Id == id).AsNoTracking().FirstOrDefaultAsync();
            var info = ObjectMapper.Map<UserInfo, UserInfoDto>(query);
            return info;
        }

        /// <summary>
        /// 添加一个用户信息
        ///</summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<UserInfoDto> CreateItemAsync(UserInfoAddDto input)
        {
            var find = _dbContext.UserInfo.Where(x => x.Email == input.Email).Any();
            if (find)
            {
                throw new PasteLoggerBoardException("登录邮箱重复，无法继续添加，请确认！");
            }

            var newu = ObjectMapper.Map<UserInfoAddDto, UserInfo>(input);
            newu.CreateDate = DateTime.Now;
            newu.IsEnable = true;//添加自定义
            newu.PassWord = input.PassWord.ToMd5Lower();
            //var updated = await _repository.InsertAsync(newu, true);
            if (!String.IsNullOrWhiteSpace(input.Grade))
            {
                var grade = _dbContext.GradeInfo.Where(x => x.Name == input.Grade).FirstOrDefault();
                if (grade != null && grade != default)
                {
                    newu.GradeId = grade.Id;
                }
                else
                {
                    newu.Grade = "";
                }
            }
            _dbContext.Add(newu);
            await _dbContext.SaveChangesAsync();
            var backinfo = ObjectMapper.Map<UserInfo, UserInfoDto>(newu);
            return backinfo;
        }
        /// <summary>
        /// 更新一个用户信息
        ///</summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<UserInfoDto> UpdateItemAsync(UserInfoUpdateDto input)
        {
            var info = await _dbContext.UserInfo.Where(x => x.Id == input.Id).FirstOrDefaultAsync();
            if (info == null || info == default)
            {
                throw new PasteLoggerBoardException("需要查询的信息不存在", "404");
            }
            var oldpass = info.PassWord;
            ObjectMapper.Map<UserInfoUpdateDto, UserInfo>(input, info);
            if (!String.IsNullOrEmpty(input.PassWord))
            {
                info.PassWord = input.PassWord.ToMd5Lower();
            }
            else
            {
                info.PassWord = oldpass;
            }
            if (!String.IsNullOrWhiteSpace(input.Grade))
            {
                var grade = _dbContext.GradeInfo.Where(x => x.Name == input.Grade).FirstOrDefault();
                if (grade != null && grade != default)
                {
                    info.GradeId = grade.Id;
                }
                else
                {
                    info.Grade = "";
                }
            }
            await _dbContext.SaveChangesAsync();
            var backinfo = ObjectMapper.Map<UserInfo, UserInfoDto>(info);
            //backinfo.Parts = await ReadUserParts(info.Id);
            return backinfo;
        }

    }
}
